package com.demo.controller;

import com.demo.domain.request.sendDemo;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo")
public class TestController {

	/**
	 * 注入kafkaTemplate
	 */
	@Autowired
	private KafkaTemplate<String, String> kafkaTemplate;

	@PostMapping("/test")
	public String testKafka(@RequestBody sendDemo model) {
//		kafkaTemplate.send(model.getTopic(), model.getPartition(),"你","好");
		ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(model.getTopic(), 0,"aaaaaa", "a,z,x,c");
			future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
				@Override
				public void onSuccess(SendResult<String, String> result) {
					System.out.println("生产者-发送消息成功：" + result.toString());
				}
				@Override
				public void onFailure(Throwable ex) {
					System.out.println("生产者-发送消息失败：" + ex.getMessage());
				}
			});
		return "success";
	}

//	//	消费者使用日志打印消息
//	@KafkaListener(topics = "foo")
//	public void receive(ConsumerRecord<?, ?> consumer) {
//		System.out.println("topic名称:" + consumer.topic() + ",key:" + consumer.key() + ",分区位置:" + consumer.partition()
//				+ ", 下标" + consumer.offset());
//	}
	
}